<?php

require_once dirname(__FILE__).'/../lib/newGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/newGeneratorHelper.class.php';

/**
 * new actions.
 *
 * @package    blog
 * @subpackage new
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class newActions extends autoNewActions
{
    
     public function executeEdit(sfWebRequest $request)
  {
    $this->blog_new = $this->getRoute()->getObject();
    $this->form = $this->configuration->getForm($this->blog_new);
    
    
    
    //Creo un objeto de la Entidad
    $blogMedium = new BlogMedium();      
    //le asigno a la relacion (new_id) el id de la noticia q se accedio
    $blogMedium->new_id = $request->getParameter('id');
    
    $this->blog_medium = $blogMedium;
    
    //Creo un objeto de la Entidad-Formulario 
    //y paso como parametro el objeto de la Entidad
    $form = new BlogMediumForm($blogMedium); 
    
    //Asigno el objeto form a la vista mediante la var: form_medium
    $this->form_medium = $form;
    
    
  }
  
  
   protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $notice = $form->getObject()->isNew() ? 'La noticia se creo satisfactoriamente.' : 'La noticia se actualizo satisfactoriamente.';

      /*
       * Codigo para eliminar cache del frontend
       */
      
        $frontend_cache_dir = sfConfig::get('sf_cache_dir').DIRECTORY_SEPARATOR.'frontend'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR.'template'.DIRECTORY_SEPARATOR.'blog'.DIRECTORY_SEPARATOR.'all';
        $cache = new sfFileCache(array('cache_dir' => $frontend_cache_dir)); // Use the same settings as the ones defined in the frontend factories.yml
        $cache->removePattern('new/index');        
        //$cache->removePattern('new/show?id=14&title_slug=hola'); 
        //$cache->removePattern('categoria/4/texto');
        
        /*
      
        $directorio_cache_frontend = sfConfig::get('sf_root_cache_dir').DIRECTORY_SEPARATOR.'frontend'.DIRECTORY_SEPARATOR.SF_ENV.DIRECTORY_SEPARATOR.'cache';       
        
        // Utiliza las mismas opciones que el archivo factories.yml de la aplicación frontend
        $cache = new sfFileCache(array('cache_dir' => $directorio_cache_frontend));
        $cache->removePattern('new/index');
        
        */
      
      try {
        $blog_new = $form->save();
      } catch (Doctrine_Validator_Exception $e) {

        $errorStack = $form->getObject()->getErrorStack();

        $message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ?  's' : null) . " with validation errors: ";
        foreach ($errorStack as $field => $errors) {
            $message .= "$field (" . implode(", ", $errors) . "), ";
        }
        $message = trim($message, ', ');

        $this->getUser()->setFlash('error', $message);
        return sfView::SUCCESS;
      }

      $this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $blog_new)));

      if ($request->hasParameter('_save_and_add'))
      {
        $this->getUser()->setFlash('notice', $notice.' Puedes agregar otra noticia debajo.');

        $this->redirect('@blog_new_new');
      }
      else
      {
        $this->getUser()->setFlash('notice', $notice);

        $this->redirect(array('sf_route' => 'blog_new_edit', 'sf_subject' => $blog_new));
      }
    }
    else
    {
      $this->getUser()->setFlash('error', 'La noticia no se creo debido a errores.', false);
    }
  }
  
  
   public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();
    
    //eliminacion de las imagenes
    
    $id = $request->getParameter('id');

    $records = Doctrine_Query::create()
      ->from('BlogMedium')
      ->whereIn('new_id', $id)
      ->execute();

    foreach ($records as $record)            
    {      
        
        $url = sfConfig::get('sf_upload_dir').'/images_news/'.$record->getUrl();
        unlink($url);
        $record->delete();
    }
    
    //eliminacion de las noticias

    $this->dispatcher->notify(new sfEvent($this, 'admin.delete_object', array('object' => $this->getRoute()->getObject())));

    if ($this->getRoute()->getObject()->delete())
    {
      $this->getUser()->setFlash('notice', 'La noticia se elimino exitosamente.');
    }

    $this->redirect('@blog_new');
  }
  
  
  protected function executeBatchDelete(sfWebRequest $request)
  {
    $ids = $request->getParameter('ids');

    $records = Doctrine_Query::create()
      ->from('BlogNew')
      ->whereIn('id', $ids)
      ->execute();

    foreach ($records as $record)
    {
      //elimina las imagenes de la noticia  
      
      $records_medium = Doctrine_Query::create()
      ->from('BlogMedium')
      ->whereIn('new_id', $record->getId())
      ->execute();
      
      foreach ($records_medium as $record_medium)
        {
          $url = sfConfig::get('sf_upload_dir').'/images_news/'.$record_medium->getUrl();
          unlink($url);          
          $record_medium->delete();
      }     
        
      //elimina la noticia  
      $this->dispatcher->notify(new sfEvent($this, 'admin.delete_object', array('object' => $record)));

      $record->delete();
    }

    $this->getUser()->setFlash('notice', 'Las noticias seleccionadas se han borrado satisfactoriamente.');
    $this->redirect('@blog_new');
  }
}
